package com.solution.admin.customer.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alipay.api.domain.DeliverAddress;
import com.solution.admin.auth.constants.AuthConstants.IS_DELETE;
import com.solution.admin.customer.constants.CustomerConstants;
import com.solution.admin.customer.dao.CompanyDao;
import com.solution.admin.customer.dao.CustomerDao;
import com.solution.admin.customer.dao.DeliveryAddressDao;
import com.solution.admin.customer.dao.DeliveryModeDao;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.entity.DeliveryAddressEntity;
import com.solution.admin.customer.entity.DeliveryModeEntity;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.settings.dao.KeyMapDao;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.common.constants.PublicStatus.ALLOWED_PAY_TYPE;
import com.solution.common.constants.PublicStatus.ALLOW_BACK_FLAG;
import com.solution.common.constants.PublicStatus.COPERATE_FLAG;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.dao.BaseDao;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.service.impl.BaseServiceImpl;
import com.solution.common.utils.string.StringUtil;

/**
 * 单位信息service实现层
 * @author solin
 * @date 2017-09-25 00:11:38
 */
@Service
public class CompanyServiceImpl extends BaseServiceImpl<CompanyEntity> implements CompanyService {

	/**
	 * 单位信息接口
	 */
	@Autowired
	private CompanyDao companyDao;
	
    /** 客户接口 */
    @Autowired
    private CustomerDao customerDao;
    
    @Autowired
	private DeliveryModeDao deliveryModeDao;
	
	@Autowired
	private KeyMapDao keyMapDao;
	
	@Autowired
	private DeliveryAddressDao deliveryAddressDao;

	protected BaseDao<CompanyEntity> getDao() {
		return this.companyDao;
	}

    /**
     * 企业注册
     * 
     * @param company
     * @param customer
     * @return int
     * @author xu_cc
     * @throws Exception
     *             exception
     * @Date 创建时间：2017年9月25日 下午5:11:38
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int doCompanyReg(CompanyEntity company, CustomerEntity customer) throws Exception {
        Long companyId = companyDao.saveCompany(company);
        if (null == companyId) {
            throw new Exception("未返回公司ID");
        }
        customer.setCompanyId(companyId);
        customerDao.saveCustomer(customer);
        return 1;
    }

	/**
	 * 保存单位信息
	 * @param companyEntity 单位信息实体
	 * @return Long 添加成功单位信息的ID
	 * @author solin
	 * @date 2017-09-25 00:11:38
	 */
    @Transactional(rollbackFor=Exception.class)
	public long saveCompany(CompanyEntity companyEntity) {
    	//公司名称校验
    	Map<String, Object> param = new HashMap<String, Object>();
        param.put("companyName", companyEntity.getCompanyName());
        List<CompanyEntity> companyList = companyDao.listCompany(param);
        if (companyList != null && companyList.size() > 0) {
        	for (int i = 0; i < companyList.size(); i++) {
        		//如果公司名称已存在，则直接返回，不再新增
        		if (companyEntity.getCompanyName().equals(companyList.get(0).getCompanyName())) {
        			return companyList.get(0).getId();
        		}
        	}
        }
    	//检查并设置默认值
    	//客户等级默认为1
    	if (null == companyEntity.getCustomerLevel()) {
    		companyEntity.setCustomerLevel(25L); //25为客户等级ID
    	}
    	//市场等级默认为1
    	if (null == companyEntity.getMarketGrade()) {
    		companyEntity.setMarketGrade(1L); //6为客户等级ID
    	}
    	//客户系数默认为1
    	if (null == companyEntity.getCustomerFactor()) {
    		// 设置默认业务员 和 默认客户系数
        	companyEntity.setCustomerFactor(CustomerConstants.DEFAULT_CUTOMER_FACTOR);
    	}
    	
    	// 设置默认业务员
    	if (null == companyEntity.getSalesmanCode()) {
        	// 设置默认的业务员
        	// 查询默认业务员工作号
        	Map<String, Object> tparam = new HashMap<String, Object>();
        	tparam.put("keyType", "defaultSalesmanCode");
        	List<KeyMapEntity> defaultSalesmanList = keyMapDao.listKeyMap(tparam);
        	companyEntity.setSalesmanCode(defaultSalesmanList.get(0).getKeyValue());
    	}
    	
    	//付款方式为立即付款
    	if (StringUtil.isEmpty(companyEntity.getAllowedPayType())) {
    		companyEntity.setAllowedPayType(ALLOWED_PAY_TYPE.IMMEDIATE.getCode());
    	}
    	//默认不允许用户退货
    	if (null == companyEntity.getAllowBackFlag()) {
    		companyEntity.setAllowBackFlag(ALLOW_BACK_FLAG.NO.getCode());
    	}
    	//默认为合作中
    	if (null == companyEntity.getCoperateFlag()) {
    		companyEntity.setCoperateFlag(COPERATE_FLAG.YES.getCode());
    	}
    	//设置默认删除状态
    	companyEntity.setIsDelete(IS_DELETE.NOT_DELETE.getId());
    	
    	//判断公司名称是否存在
    	
    	//保存公司基本信息
		Long companyId = companyDao.saveCompany(companyEntity);
		//设置默认配件方式
		if (companyId > 0){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("keyType", "deliveryMode");
			List<KeyMapEntity> keyList = keyMapDao.listKeyMap(paramMap);
			List<DeliveryModeEntity> deliveryModeList = new ArrayList<DeliveryModeEntity>();
			for (int i = 0; i < keyList.size(); i++) {
				DeliveryModeEntity deliveryModeEntity = new DeliveryModeEntity();
				deliveryModeEntity.setCompanyId(companyId);
				deliveryModeEntity.setModeValue(keyList.get(i).getKeyValue());
				deliveryModeEntity.setModeName(keyList.get(i).getKeyIntro());
				deliveryModeEntity.setCreater(companyEntity.getCreater());
				//以普通物流为默认物流
				if ("2".equals(keyList.get(i).getKeyValue())) {
					deliveryModeEntity.setDefaultFlag("1");
				}
				deliveryModeList.add(deliveryModeEntity);
			}
			deliveryModeDao.deleteDeliveryModeByCompanyId(companyId);
			deliveryModeDao.batchSaveDeliveryMode(deliveryModeList);
			
		}
		//保存公司扩展地址
		if (companyId > 0 && companyEntity.getCompanyAddressExtendInfo() != null && companyEntity.getCompanyAddressExtendInfo().size() > 0) {
			for (int i= 0; i < companyEntity.getCompanyAddressExtendInfo().size(); i++){
				companyEntity.getCompanyAddressExtendInfo().get(i).setCompanyId(companyId);
			}
			companyDao.insertAddress(companyEntity.getCompanyAddressExtendInfo());
		} 
		
		//将公司收货地址设置为没有默认地址或者没有收货地址的客户的默认地址
		if (companyId > 0 
				&& null != companyEntity.getProvinceCode()
						&& null != companyEntity.getCityCode()
								&& null != companyEntity.getAreaCode()
										&& null != companyEntity.getStreetCode()
											&&  null != companyEntity.getAddress()
				) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("companyId", companyId);
			List<CustomerEntity> nonCustomers = customerDao.getCustomersOfNonDefaultAddress(paramMap);
			if (null != nonCustomers && nonCustomers.size() > 0) {
				//注：一般情况下只会有一个客户，所以没有采用批量插入
				for (CustomerEntity customer : nonCustomers) {
					DeliveryAddressEntity deliveryAddressInfo = new DeliveryAddressEntity();
					deliveryAddressInfo.setCustomerId(customer.getId());
					deliveryAddressInfo.setReceiverName(customer.getUserName());
					deliveryAddressInfo.setMobile(customer.getMobile());
					deliveryAddressInfo.setProvinceCode(companyEntity.getProvinceCode());
					deliveryAddressInfo.setProvinceName(companyEntity.getProvinceName());
					deliveryAddressInfo.setCityCode(companyEntity.getCityCode());
					deliveryAddressInfo.setCityName(companyEntity.getCityName());
					deliveryAddressInfo.setAreaCode(companyEntity.getAreaCode());
					deliveryAddressInfo.setAreaName(companyEntity.getAreaName());
					deliveryAddressInfo.setStreetCode(companyEntity.getStreetCode());
					deliveryAddressInfo.setStreetName(companyEntity.getStreetName());
					deliveryAddressInfo.setAddress(companyEntity.getAddress());
					deliveryAddressInfo.setIsDefault(1);
					deliveryAddressInfo.setIsDelete(IS_DELETE.NOT_DELETE.getId());
					deliveryAddressInfo.setStatus(STATUS.ENABLED.getId());
					deliveryAddressInfo.setCreater(companyEntity.getCreater());
					deliveryAddressDao.saveDeliveryAddress(deliveryAddressInfo);
				}
			}
		}
		
		return companyId;
	}

	/**
	 * 分页查询单位信息
	 * @param pageParam 分页参数
	 * @param paramMap 查询参数
	 * @return PageBean 分页参数和分页数据
	 * @author solin
	 * @date 2017-09-25 00:11:38
	 */
	@Override
	public PageBean listCompanyPage(PageParam pageParam, Map<String, Object> paramMap) {
		return companyDao.listCompanyPage(pageParam, paramMap);
	}
	
	/**
	 * 根据ID查询用户信息
	 * @param id 用户id
	 * @return companyEntity 用户对象
	 * @author solin
	 * @date 2017-09-25 00:11:38
	 */
	public CompanyEntity getCompanyById(Long id) {
		return companyDao.getById(id.longValue());
	}

	/**
	 * 更新单位信息
	 * @param companyEntity 用户实体
	 * @return Long 更新是否成功，>1代表更新成功
	 * @author solin
	 * @date 2017-09-25 00:11:38
	 */
	@Override
	public int updateCompany(CompanyEntity companyEntity) {
		int result = companyDao.updateCompany(companyEntity);
		if (result > 0) {
			companyDao.deleteAddressByCompanyId(companyEntity.getId());
			if (companyEntity.getCompanyAddressExtendInfo() != null && companyEntity.getCompanyAddressExtendInfo().size() > 0) {
				for (int i= 0; i < companyEntity.getCompanyAddressExtendInfo().size(); i++){
					companyEntity.getCompanyAddressExtendInfo().get(i).setCompanyId(companyEntity.getId());
				}
				companyDao.insertAddress(companyEntity.getCompanyAddressExtendInfo());
			}
		} 
		
		//将公司收货地址设置为没有默认地址或者没有收货地址的客户的默认地址
		if (companyEntity.getId() > 0 
				&& null != companyEntity.getProvinceCode()
						&& null != companyEntity.getCityCode()
								&& null != companyEntity.getAreaCode()
										&& null != companyEntity.getStreetCode()
											&&  null != companyEntity.getAddress()
				) {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("companyId", companyEntity.getId());
			List<CustomerEntity> nonCustomers = customerDao.getCustomersOfNonDefaultAddress(paramMap);
			if (null != nonCustomers && nonCustomers.size() > 0) {
				//注：一般情况下只会有一个客户，所以没有采用批量插入
				for (CustomerEntity customer : nonCustomers) {
					DeliveryAddressEntity deliveryAddressInfo = new DeliveryAddressEntity();
					deliveryAddressInfo.setCustomerId(customer.getId());
					deliveryAddressInfo.setReceiverName(customer.getUserName());
					deliveryAddressInfo.setMobile(customer.getMobile());
					deliveryAddressInfo.setProvinceCode(companyEntity.getProvinceCode());
					deliveryAddressInfo.setProvinceName(companyEntity.getProvinceName());
					deliveryAddressInfo.setCityCode(companyEntity.getCityCode());
					deliveryAddressInfo.setCityName(companyEntity.getCityName());
					deliveryAddressInfo.setAreaCode(companyEntity.getAreaCode());
					deliveryAddressInfo.setAreaName(companyEntity.getAreaName());
					deliveryAddressInfo.setStreetCode(companyEntity.getStreetCode());
					deliveryAddressInfo.setStreetName(companyEntity.getStreetName());
					deliveryAddressInfo.setAddress(companyEntity.getAddress());
					deliveryAddressInfo.setIsDefault(1);
					deliveryAddressInfo.setIsDelete(IS_DELETE.NOT_DELETE.getId());
					deliveryAddressInfo.setStatus(STATUS.ENABLED.getId());
					deliveryAddressInfo.setCreater(companyEntity.getCreater());
					deliveryAddressDao.saveDeliveryAddress(deliveryAddressInfo);
				}
			}
		}
		
		return result;
	}
	
	/**
	 * 更新单位开票信息
	 * @param companyEntity 用户实体
	 * @return Long 更新是否成功，>1代表更新成功
	 * @author solin
	 * @date 2017-09-25 00:11:38
	 */
	@Override
	public int updateCompanyBillingInfo(CompanyEntity companyEntity) {
		int result = companyDao.updateCompany(companyEntity);
		return result;
	}
	
	
	/**
	 * 根据条件查询单位信息
	 * @param param
	 * @return 数据列表
	 * @author solin
	 * @date 2017-09-25 00:11:38
	 */
	@Override
	public List<CompanyEntity> listCompany( Map<String, Object> param){
		return  companyDao.listCompany(param);
	}
	
	/**
	 * 删除单位信息
	 * @param 
	 * @return int 返回删除记录条数
	 * @author solin
	 * @date 2017-09-25 00:11:38
	 */
	public int deleteCompanyById(long id){
		int result = companyDao.deleteById(id);
		if (result > 0) {
			companyDao.deleteAddressByCompanyId(id);
		}
		return result;
	}

	/**
	 * 根据公司ID获取业务员信息
	 * @param companyId
	 * @return
	 * @author xkl
	 * @date 2018年2月9日 下午5:14:03
	 */
	@Override
	public Map<String, Object> getSalesmanByCompanyId(Long companyId) {
		return companyDao.getSalesmanByCompanyId(companyId);
	}
	
}
